import time
import tkinter as tk
from tkinter import ttk, Text
from tkinter.ttk import Label

from common import config, utils
from common.config import APP_TITLE, TABLE_COLUMNS


class Item:
    def __init__(self, sid, user_id, device_id, proxy_ip, real_ip, update_at, status, desc):
        self.sid = sid
        self.user_id = user_id
        self.device_id = device_id
        self.real_ip = real_ip
        self.proxy_ip = proxy_ip
        self.update_at = update_at
        self.status = status
        self.desc = desc

class Content:
    def __init__(self):
        self.sessions = {}
        self.log_text = ""
class Component:
    def __init__(self):
        self.root = tk.Tk()
        self.root.title(APP_TITLE)
        self.root.resizable(False, False)
        self.menu_bar = tk.Menu(self.root)
        self.root.config(menu=self.menu_bar)
        self.file_menu = tk.Menu(self.menu_bar, tearoff=0)
        self.menu_bar.add_cascade(label="功能", menu=self.file_menu)
        self.file_menu.add_command(label="退出", command=self.root.quit)
        self.help_menu = tk.Menu(self.menu_bar, tearoff=0)
        self.menu_bar.add_cascade(label="帮助", menu=self.help_menu)
        self.help_menu.add_command(label="使用说明", command=self.root.quit)
        self.help_menu.add_command(label="关于", command=self.root.quit)
        self.frame = tk.Frame(self.root)
        self.frame.pack(padx=10, pady=10)
        self.table = ttk.Treeview(self.frame, columns=TABLE_COLUMNS, show="headings")
        for col in TABLE_COLUMNS:
            self.table.heading(col, text=col["title"])
            self.table.column(col, width=col["width"])
        self.table.pack(fill=tk.BOTH, expand=True)
        self.log_text = Text(self.root, bg='black', fg='white', state='disabled', height=10)
        self.log_text.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
    def show(self):
        self.root.wm_protocol("WM_DELETE_WINDOW", self.close)
        self.root.mainloop()
    def append_log(self, text):
        self.log_text.configure(state='normal')
        current_text = self.log_text.get("1.0", tk.END)
        current_time = time.strftime('%Y-%m-%d %H:%M:%S')
        new_text = f'[{current_time}]： {text}\n'
        total_text = current_text + new_text
        if len(total_text) > config.MAX_LOG_TEXT:
            excess_characters = len(total_text) - config.MAX_LOG_TEXT
            # 获取当前文本按行分割后的列表
            lines = total_text.splitlines(True)
            # 计算需要删除的行数，假设平均每行有一定数量的字符（这里简单按平均每行20个字符估算，可根据实际调整）
            lines_to_remove = excess_characters // 20
            if lines_to_remove >= len(lines):
                # 如果要删除的行数超过总现有行数，直接清空文本框
                self.log_text.delete("1.0", tk.END)
            else:
                # 删除前面多余的行，保留后面的内容
                self.log_text.delete("1.0", f"{len(lines) - lines_to_remove}.0")
        self.log_text.insert(tk.END, new_text)
        self.log_text.configure(state='disabled')
        self.log_text.yview(tk.END)
    def append_row(self, items):
        for item in items:
            self.table.insert("", tk.END, iid=item.sid,
                              values=(item.user_id, item.device_id, item.proxy_ip, item.update_at, item.desc),
                              tags=item.status
            )
            self.table.tag_configure(item.status, foreground="purple")
    def update_row(self, item: Item):
        self.table.item(
            item.sid,
            values=(item.user_id, item.device_id, item.proxy_ip, item.update_at, item.desc),
            tags=("success" if item.status == "success" else "failure")
        )
        self.table.tag_configure("success", foreground="green")
        self.table.tag_configure("failure", foreground="red")
    def close(self):
        self.root.quit()
class Dashboard:
    def __init__(self):
        self.content = Content()
        self.component = Component()

    def init_table_row(self, items):
        for item in items:
            current_time = time.strftime('%Y-%m-%d %H:%M:%S')
            self.content.sessions[item["sid"]] = Item(
                item["sid"],
                item["username"],
                utils.mark_text_field(item["device_id"], 8),
                utils.mark_ip_field(item["proxy_ip"]),
                "",
                f"{current_time}",
                "连接中",
                "等待初始化"
            )
        self.component.append_row(self.content.sessions.values())
    def update_row(self, sid, status, desc):
        item: Item = self.content.sessions.get(sid)
        if item is None:
            return
        item.status = status
        item.desc = desc
        item.update_at = time.strftime('%Y-%m-%d %H:%M:%S')
        self.content.sessions[sid] = item
        self.component.update_row(item)
    def pop_tips(self, message):
        print("1")
    def append_log(self, text):
        self.component.append_log(text)
    def show(self):
        self.component.show()
    def start(self):
        self.content.sessions = {}

dashboard = Dashboard()
